<template>
    <div class="base-main">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="130px">
            <h1>基础信息</h1>
            <el-form-item prop="distributerTitle" label="分销员名称">
                <el-input
                    v-model="form.distributerTitle"
                    class="custom-input"
                    maxlength="6"
                    show-word-limit
                    :disabled="isDisabled"
                    placeholder="请填写标题"></el-input>
            </el-form-item>
            <el-form-item prop="becomeDtbor" label="成为分销员">
                <el-radio-group v-model="form.becomeDtbor" :disabled="isDisabled">
                    <el-radio :label="1">主动申请</el-radio>
                    <el-radio :label="2" disabled>购买指定商品（敬请期待）</el-radio>
                </el-radio-group>
            </el-form-item>
            <!-- todo:申请为分销员type 输入框值最小为多少-->
            <el-form-item label="申请成为分销员" prop="applyDtbor">
                <el-radio-group v-model="form.applyDtbor" @change="switchChange" :disabled="isDisabled">
                    <div class="radio-type">
                        <el-radio :label="0">用户手机号注册成功</el-radio>
                    </div>
                    <div class="radio-type">
                        <el-radio :label="1">累计购买金额达</el-radio>
                        <el-input-number
                            v-model="form.amountOrNum"
                            :disabled="isDisabled || form.applyDtbor != 1"
                            class="custom-number-small"
                            :min="0"
                            :max="99999999"
                            :precision="0"
                            :controls="false" /><span class="tip">元</span>
                    </div>
                    <div class="radio-type">
                        <el-radio :label="2">累计购买</el-radio>
                        <el-input-number
                            v-model="form.amountOrNum2"
                            :disabled="isDisabled || form.applyDtbor != 2"
                            class="custom-number-small"
                            :min="0"
                            :max="99999999"
                            :precision="0"
                            :controls="false" /><span class="tip">次</span>
                    </div>
                </el-radio-group>
            </el-form-item>
            <el-form-item prop="bindFans" label="绑定粉丝">
                <el-radio-group v-model="form.bindFans" :disabled="isDisabled">
                    <el-radio :label="1">粉丝手机号注册时</el-radio>
                    <el-radio :label="2">粉丝下单并支付成功时</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item prop="bindFansValid" label="绑定时效">
                <el-radio-group v-model="form.bindFansValid" :disabled="isDisabled">
                    <el-radio :label="1">永久</el-radio>
                </el-radio-group>
            </el-form-item>
            <h1>分销模式</h1>
            <el-form-item prop="inviteSwitch" label="邀请佣金">
                <el-radio-group v-model="form.inviteSwitch" :disabled="isDisabled">
                    <el-radio :label="1">关闭</el-radio>
                    <el-radio :label="2"
                        >开启
                        <span class="radio-tip">（开启后，分销员支持邀请分销员，邀请人可获得邀请佣金）</span></el-radio
                    >
                </el-radio-group>
            </el-form-item>
            <el-form-item prop="benefitMode" label="分佣方式">
                <el-radio-group v-model="form.benefitMode" :disabled="isDisabled">
                    <el-radio :label="2">现金奖励</el-radio>
                    <el-radio :label="1">积分奖励 <span class="radio-tip">（1元=100积分）</span></el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item prop="checkPoint" label="结算时间">
                <el-radio-group v-model="form.checkPoint" :disabled="isDisabled">
                    <el-radio :label="1">过售后期</el-radio>
                    <el-radio :label="2"
                        >确认收货 <span class="radio-tip">（风险较大，若订单发生退款，则佣金无法退回）</span></el-radio
                    >
                </el-radio-group>
            </el-form-item>
        </el-form>
        <div class="form-footer">
            <el-button type="primary" @click="saveHandler" :disabled="isDisabled">保存</el-button>
        </div>
    </div>
</template>

<script setup>
import { onUnmounted, onMounted, computed, reactive, ref, unref } from 'vue';
import { ElMessage } from 'element-plus';
import { isDayBefore, dateDiff, cloneDeep, format } from '@/commons/utils';
import request from '@/request/index';
import { setLayout, resetLayout } from '@/hooks/layout';
import store from '@/store/index';

const useAuth = store.useAuthStore();
const permissions = useAuth.permissions;
const isDisabled = computed(() => {
    return !permissions.has('distribution_set:base_edit');
});

const form = reactive({
    tab: 1,
    distributerTitle: '分销员',
    becomeDtbor: 1,
    needMobile: 1,
    applyDtbor: 0,
    amountOrNum: null,
    amountOrNum2: null,
    bindFans: 1,
    bindFansValid: 1,
    inviteSwitch: 1,
    benefitMode: 2,
    checkPoint: 1
});
const formRef = ref();

const checkType = (rule, val, callback) => {
    if (form.applyDtbor == 1 && form.amountOrNum === null) {
        return callback(new Error('请填写累计购买金额'));
    }
    if (form.applyDtbor == 2 && form.amountOrNum2 === null) {
        return callback(new Error('请填写累计购买次数'));
    }
    callback();
};
const rules = reactive({
    distributerTitle: [
        { required: true, message: '请输入分销员名称', trigger: 'blur' },
        { min: 1, max: 6, message: '最长不超过6个字', trigger: 'blur' }
    ],
    applyDtbor: [{ required: true, trigger: 'change', validator: checkType }]
});

const switchChange = val => {
    // todo:输入框值置空
    form.amountOrNum = null;
    form.amountOrNum2 = null;
};

const saveHandler = async () => {
    if (!unref(formRef)) return;
    await unref(formRef).validate(async (valid, fields) => {
        if (valid) {
            const params = cloneDeep(form);
            if (params.applyDtbor == 2) {
                params.amountOrNum = params.amountOrNum2 || 0;
            } else if (params.applyDtbor == 1) {
                params.amountOrNum = params.amountOrNum ? params.amountOrNum * 100 : 0;
            }
            delete params.amountOrNum2;
            const { code } = await request('distributionSettingsSave', params);
            if (code !== 0) {
                return;
            }
            ElMessage({
                type: 'success',
                message: '保存成功'
            });
        } else {
            unref(formRef).scrollToField(Object.keys(fields)?.[0]);
        }
    });
};

const clearValidate = field => {
    unref(formRef).clearValidate(field);
};

const validateField = field => {
    unref(formRef).validateField(field);
};

const getDetail = async () => {
    const { data } = await request('distributionSettingsInfo', {
        tab: 1
    });
    const {
        distributerTitle,
        becomeDtbor,
        needMobile,
        applyDtbor,
        amountOrNum,
        bindFans,
        bindFansValid,
        inviteSwitch,
        benefitMode,
        checkPoint
    } = (data || {})?.info || {};
    form.distributerTitle = distributerTitle || '分销员';
    form.becomeDtbor = becomeDtbor || 1;
    form.needMobile = needMobile || 1;
    form.applyDtbor = applyDtbor || 0;
    form.amountOrNum = form.applyDtbor != 1 ? null : amountOrNum;
    form.amountOrNum2 = form.applyDtbor != 2 ? null : amountOrNum;
    form.amountOrNum = form.amountOrNum ? form.amountOrNum / 100 : form.amountOrNum;
    form.bindFans = bindFans || 1;
    form.bindFansValid = bindFansValid || 1;
    form.inviteSwitch = inviteSwitch || 1;
    form.benefitMode = benefitMode || 2;
    form.checkPoint = checkPoint || 1;
};

onMounted(() => {
    setLayout('custom-base-layout');
    getDetail();
});
onUnmounted(() => {
    resetLayout('custom-base-layout');
});
</script>

<style lang="scss">
.custom-base-layout {
    min-height: calc(100vh - 260px) !important;
    max-height: calc(100vh - 260px);
    overflow-y: auto;
}
</style>
<style lang="scss" scoped>
.base-main {
    :deep {
        .el-form-item__label {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #33302d;
        }
    }
    h1 {
        position: relative;
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #33302d;
        padding-left: 15px;
        margin: 25px 0;
        &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 15%;
            width: 3px;
            height: 70%;
            background-color: var(--el-color-primary);
        }
        &:first-of-type {
            margin-top: 10px;
        }
    }
    .custom-input {
        width: 290px;
    }
    .radio-type {
        display: flex;
        align-items: center;
        width: 100%;
        margin-bottom: 8px;
        font-size: 14px;
        &:last-of-type {
            margin-top: 8px;
        }
        .el-radio {
            margin-right: 4px;
        }
        .custom-number-small {
            margin-bottom: -4px;
        }
        .tip {
            margin-left: 4px;
        }
    }
    .custom-number-small {
        width: 80px;
    }
    .radio-tip {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
    }
    .form-footer {
        position: absolute;
        bottom: 0;
        left: 1px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: calc(100% - 1px);
        height: 70px;
        background-color: #fff;
        .el-button {
            width: 80px;
        }
    }
}
</style>
